import React, { useState, useEffect } from 'react';
import { InboxOutlined } from '@ant-design/icons';
import type { UploadProps } from 'antd';
import type { UploadRequestOption } from "rc-upload/lib/interface";
import { createStyles } from 'antd-style';
import { message, Upload, Progress, Button, Spin } from 'antd';
import { directUploadFile } from '@/services/file/api';
import FragmentUploader from "./fragment-uploader"

const FileMaxSize = 1024 * 1024 * 1 // 1M

const useStyles = createStyles(({ token }) => {
  return {
    action: {
      background: "#fff",
      padding: "16px",
      marginBottom: "16px",
    },
    title: {
      marginBottom: "16px"
    }
  };
});

const { Dragger } = Upload;


interface ChildComponentProps {
  onUpload: () => void;
}

  // 大文件分片上传
  const fragmentUploader = new FragmentUploader()

const UploadComp: React.FC<ChildComponentProps> = ({ onUpload }) => {
  const { styles } = useStyles();

  const [uploading, setUploading] = useState(false);
  const [isBigFile, setIsBigFile] = useState(false);
  const [progress, setProgress] = useState(0)

  useEffect(() => {
    fragmentUploader.setOnUploadProgress((progress) => {
      setProgress(progress);
    });
  });

  const customRequest = async (options: UploadRequestOption) => {
    const { file, onSuccess, onError } = options;
    setUploading(true);

    if (file.size <= FileMaxSize) {
      setIsBigFile(false)
      const formData = new FormData()
      formData.append('file', file)
      try {
        await directUploadFile(formData)
        onSuccess?.({ result: '上传成功' }, file)
      } catch (err) {
        onError?.(err instanceof Error ? err : new Error(String(err)))
      } finally {
        setUploading(false)
      }
    } else {
      setIsBigFile(true)
      try {
        await fragmentUploader.HandleUpload(file as File)
        onSuccess?.({ result: '上传成功' }, file)
      } catch (err) {
        onError?.(err instanceof Error ? err : new Error(String(err)))
      } finally {
        setUploading(false)
        setIsBigFile(false)
        fragmentUploader.reset()
      }
    }
  }

  const handleAbort = (e: React.MouseEvent<HTMLButtonElement>) => {
    e.stopPropagation()
    fragmentUploader.abort()
  }

  const props: UploadProps = {
    name: 'file',
    multiple: false,
    showUploadList: false,
    onChange(info) {
      const { status } = info.file;
      if (status === 'done') {
        message.success(`${info.file.name} 文件上传成功`);
        onUpload()
      } else if (status === 'error') {
        console.log("onChange", info.file.error.status)
        if (info.file.error?.status == 401) {
          const url = new URL("/user/login", window.location.origin);
          url.searchParams.set('redirect', location.pathname);
          window.location.href = url.toString()

          message.error(info.file?.response?.message);
        } else {
          message.error(`${info.file.name} file upload failed.`);
        }
      }
    },
    customRequest: customRequest,
  };

  return (
    <div className={styles.action}>
      <Dragger {...props} >
        <p className="ant-upload-drag-icon">
          <Spin spinning={uploading}>
            
          <InboxOutlined  /> </Spin>
 
        </p>
        {/* <p className="ant-upload-text">Click or drag file to this area to upload</p> */}
        <p className="ant-upload-hint">
          支持单文件上传，测试上传下载服务
        </p>
        {isBigFile &&
          (<div style={{ display: "flex" }}><Progress percent={progress} />
            <span style={{ marginLeft: 8, whiteSpace: 'nowrap', fontSize: 12, marginTop: 2.5 }}>
              {progress == 0 && <span >数据准备中</span>}
              {progress > 0 && progress < 100 && <span style={{color: "#ff4d4f"}} onClick={handleAbort}>停止上传</span>}
            </span>
          </div>)
        }
      </Dragger>
    </div>
  )
}


export default UploadComp;